package net.huashitong.ssydt.provider.sys.service;

import net.huashitong.ssydt.exceptions.ServiceException;
import net.huashitong.ssydt.provider.sys.mapper.SsSysTableMapper;
import net.huashitong.ssydt.provider.utils.StringUtils;
import net.huashitong.ssydt.provider.utils.date.DateUtils;
import net.huashitong.ssydt.sys.entity.SsSysTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author huiyang.yu
 */
@Service
public class SsSysTableServiceImpl implements SsSysTableService {

    @Autowired
    private SsSysTableMapper dao;

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public String updateMaxId(String preStr, String tableName) {
        if(StringUtils.isBlank(preStr)) {
            preStr = new StringBuilder(8).append(DateUtils.getDate("yyyyMMdd")).toString();
        }
        SsSysTable ssSysTable = dao.getByTableName(tableName);

        if (ssSysTable == null) {
            throw new ServiceException("Table strategy is empty");
        }

        if (preStr.length() != ssSysTable.getPreNumber()) {
            throw new ServiceException("Table strategy preStr is error length for developer");
        }

        String serialStr = ssSysTable.getMaxSerialNum();
        Long maxSysIdNum = Long.parseLong(serialStr);
        maxSysIdNum += 1;

        StringBuilder maxSysId = new StringBuilder(20).append(preStr).append(maxSysIdNum.toString());
        ssSysTable.setMaxId(maxSysId.toString());
        ssSysTable.setMaxSerialNum(maxSysIdNum.toString());
        dao.updateMaxId(ssSysTable);//更新回到数据库持久态

        return maxSysId.toString();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public String updateMaxId(String tableName) {
        StringBuilder preStr = new StringBuilder(8).append(DateUtils.getDate("yyyyMMdd"));
        return updateMaxId(preStr.toString(), tableName);
    }
}
